package com.sh.ndt.common.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.log4j.Logger;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;

/**
 * A subclass of Spring Framework's StoredProcedure
 *
 * @author Manjula Hosadurga
 */
public class ExecuteStoredProcedure extends StoredProcedure {

    private static final Logger LOGGER = Logger.getLogger(ExecuteStoredProcedure.class);
    private String storedProcedureName;

    public ExecuteStoredProcedure(DataSource ds, String spName,
            SqlParameter[] sqlParams) {
        super(ds, spName);
        super.setParameters(sqlParams);
        this.storedProcedureName = spName;
        compile();
    }

    public Map executeStoredProcs(Map inputs) {
        constructSPCallSyntax(storedProcedureName, inputs);
        LOGGER.debug(new StringBuffer("Calling SP ").append(storedProcedureName));

        return super.execute(inputs);
    }

   public Map executeStoredProcsWitnNoReturn(Map inputs) {
        constructSPCallSyntax(storedProcedureName, inputs);
        LOGGER.debug(new StringBuffer("Calling SP ").append(storedProcedureName));

       return super.execute(inputs);
    }
   
   
   
    private void constructSPCallSyntax(String storedProcedureName, Map inputParams) {

        Iterator it = inputParams.keySet().iterator();

        StringBuffer query = new StringBuffer();
        query.append(storedProcedureName);
        query.append(" ");

        while (it.hasNext()) {
            String key = (String) it.next();

            if (key.contains("xml")) {
                //
                // xml value passed will be too long - so skip
                //
                query.append("@" + key + "=" + "string too long to print in this method" + ", ");
            } else {
                Object value = inputParams.get(key);
                query.append("@" + key + "=" + value + ", ");
            }
        }
        /**
         * Used only for debugging purpose
         */
        LOGGER.debug("\n"
                + "<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> \n"
                + "SP CALL WITH PARAMS : " + query.toString().substring(0, (query.length() - 2)) + "\n"
                + "<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>");

    }

}
